using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Entities;
using Book.Blog.Core.Interfaces;
using System.Linq;

namespace Book.Blog.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PostsController : ControllerBase
    {
        private readonly IRepository<Post> _postRepository;
        private readonly IRepository<Category> _categoryRepository;
        private readonly IRepository<Tag> _tagRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly UserManager<User> _userManager;

        public PostsController(
            IRepository<Post> postRepository,
            IRepository<Category> categoryRepository,
            IRepository<Tag> tagRepository,
            IUnitOfWork unitOfWork,
            UserManager<User> userManager)
        {
            _postRepository = postRepository;
            _categoryRepository = categoryRepository;
            _tagRepository = tagRepository;
            _unitOfWork = unitOfWork;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取文章列表（支持分页、分类、标签、搜索、是否包含草稿）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="category">分类slug</param>
        /// <param name="tag">标签slug</param>
        /// <param name="search">搜索关键字</param>
        /// <param name="includeDrafts">是否包含草稿</param>
        /// <returns>文章分页列表</returns>
        [HttpGet]
        public async Task<ActionResult<PostPagedListDTO>> GetPosts(
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string? category = null,
            [FromQuery] string? tag = null,
            [FromQuery] string? search = null,
            [FromQuery] bool includeDrafts = false)
        {
            var query = _unitOfWork.Posts.GetAllAsync().Result.AsQueryable();

            // 只显示已发布的文章（除非请求包含草稿）
            if (!includeDrafts)
            {
                query = query.Where(p => p.IsPublished);
            }

            // 按分类筛选
            if (!string.IsNullOrEmpty(category))
            {
                query = query.Where(p => p.Category != null && p.Category.Slug == category);
            }

            // 按标签筛选
            if (!string.IsNullOrEmpty(tag))
            {
                query = query.Where(p => p.Tags.Any(t => t.Slug == tag));
            }

            // 搜索
            if (!string.IsNullOrEmpty(search))
            {
                query = query.Where(p => 
                    p.Title.Contains(search) || 
                    p.Content.Contains(search) || 
                    p.Summary.Contains(search));
            }

            var totalCount = query.Count();
            var items = await query
                .OrderByDescending(p => p.CreatedTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(p => new PostListDTO
                {
                    Id = p.Id,
                    Title = p.Title,
                    Summary = p.Summary,
                    Slug = p.Slug,
                    IsPublished = p.IsPublished,
                    PublishTime = p.PublishTime,
                    ViewCount = p.ViewCount,
                    LikeCount = p.LikeCount,
                    CommentCount = p.CommentCount,
                    CreatedTime = p.CreatedTime,
                    UserId = p.AuthorId,
                    UserName = p.Author.UserName,
                    UserAvatar = p.Author.Avatar,
                    CategoryName = p.Category != null ? p.Category.Name : null,
                    TagNames = p.Tags.Select(t => t.Name).ToList()
                })
                .ToListAsync();

            return new PostPagedListDTO
            {
                Items = items,
                TotalCount = totalCount,
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
                HasPreviousPage = pageIndex > 1,
                HasNextPage = pageIndex < (int)Math.Ceiling(totalCount / (double)pageSize)
            };
        }

        /// <summary>
        /// 获取文章详情
        /// </summary>
        /// <param name="id">文章ID</param>
        /// <returns>文章详情</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<PostDTO>> GetPost(Guid id)
        {
            var post = await _unitOfWork.Posts.GetByIdAsync(id);
            if (post == null)
            {
                return NotFound();
            }

            // 增加浏览次数
            post.ViewCount++;
            await _unitOfWork.SaveChangesAsync();

            return new PostDTO
            {
                Id = post.Id,
                Title = post.Title,
                Content = post.Content,
                Summary = post.Summary,
                Slug = post.Slug,
                IsDraft = post.IsDraft,
                IsPublished = post.IsPublished,
                PublishTime = post.PublishTime,
                ViewCount = post.ViewCount,
                LikeCount = post.LikeCount,
                CommentCount = post.CommentCount,
                CreatedTime = post.CreatedTime,
                UpdatedTime = post.UpdatedTime,
                UserId = post.AuthorId,
                UserName = post.Author.UserName,
                UserAvatar = post.Author.Avatar,
                CategoryId = post.CategoryId,
                CategoryName = post.Category?.Name,
                Tags = post.Tags.Select(t => new TagDTO
                {
                    Id = t.Id,
                    Name = t.Name,
                    Description = t.Description,
                    Slug = t.Slug,
                    PostCount = t.PostCount
                }).ToList()
            };
        }

        /// <summary>
        /// 创建新文章（需登录）
        /// </summary>
        /// <param name="model">文章信息</param>
        /// <returns>新建文章详情</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "title": "新文章标题",
        ///   "content": "文章内容",
        ///   "summary": "摘要",
        ///   "slug": "new-post",
        ///   "isDraft": false,
        ///   "isPublished": true,
        ///   "categoryId": "分类ID",
        ///   "tagIds": ["标签ID1", "标签ID2"]
        /// }
        /// </remarks>
        [HttpPost]
        [Authorize]
        public async Task<ActionResult<PostDTO>> CreatePost(CreatePostDTO model)
        {
            var user = await _userManager.GetUserAsync(User);
            var category = model.CategoryId.HasValue ? await _unitOfWork.Categories.GetByIdAsync(model.CategoryId.Value) : null;
            var tags = new List<Tag>();

            if (model.TagIds != null)
            {
                foreach (var tagId in model.TagIds)
                {
                    var tag = await _unitOfWork.Tags.GetByIdAsync(tagId);
                    if (tag != null)
                    {
                        tags.Add(tag);
                    }
                }
            }

            var post = new Post
            {
                Title = model.Title,
                Content = model.Content,
                Summary = model.Summary,
                Slug = model.Slug,
                IsDraft = model.IsDraft,
                IsPublished = model.IsPublished,
                PublishTime = model.IsPublished ? DateTime.UtcNow : null,
                Author = user,
                Category = category
            };

            foreach (var tag in tags)
            {
                post.Tags.Add(tag);
            }

            await _unitOfWork.Posts.AddAsync(post);
            await _unitOfWork.SaveChangesAsync();

            // 更新分类和标签的文章计数
            if (category != null)
            {
                category.PostCount = category.Posts.Count;
            }
            foreach (var tag in tags)
            {
                tag.PostCount = tag.Posts.Count;
            }
            await _unitOfWork.SaveChangesAsync();

            return await GetPost(post.Id);
        }

        /// <summary>
        /// 更新文章（需作者或管理员）
        /// </summary>
        /// <param name="id">文章ID</param>
        /// <param name="model">文章信息</param>
        /// <returns>无内容</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "title": "新文章标题",
        ///   "content": "文章内容",
        ///   "summary": "摘要",
        ///   "slug": "new-post",
        ///   "isDraft": false,
        ///   "isPublished": true,
        ///   "categoryId": "分类ID",
        ///   "tagIds": ["标签ID1", "标签ID2"]
        /// }
        /// </remarks>
        [HttpPut("{id}")]
        [Authorize]
        public async Task<IActionResult> UpdatePost(Guid id, UpdatePostDTO model)
        {
            var post = await _unitOfWork.Posts.GetByIdAsync(id);
            if (post == null)
            {
                return NotFound();
            }

            var user = await _userManager.GetUserAsync(User);
            if (post.AuthorId != user.Id && !await _userManager.IsInRoleAsync(user, "Admin"))
            {
                return Forbid();
            }

            post.Title = model.Title;
            post.Content = model.Content;
            post.Summary = model.Summary;
            post.Slug = model.Slug;
            post.IsDraft = model.IsDraft;

            // 如果文章从未发布变为发布状态
            if (!post.IsPublished && model.IsPublished)
            {
                post.PublishTime = DateTime.UtcNow;
            }
            post.IsPublished = model.IsPublished;
            post.UpdatedAt = DateTime.UtcNow;

            // 更新分类
            if (model.CategoryId != post.CategoryId)
            {
                var oldCategory = post.Category;
                var newCategory = model.CategoryId.HasValue ? await _unitOfWork.Categories.GetByIdAsync(model.CategoryId.Value) : null;
                
                post.Category = newCategory;
                
                if (oldCategory != null)
                {
                    oldCategory.PostCount = oldCategory.Posts.Count - 1;
                }
                if (newCategory != null)
                {
                    newCategory.PostCount = newCategory.Posts.Count + 1;
                }
            }

            // 更新标签
            if (model.TagIds != null)
            {
                // 先移除所有旧标签
                foreach (var tag in post.Tags.ToList())
                {
                    post.Tags.Remove(tag);
                    tag.PostCount = tag.Posts.Count - 1;
                }

                // 添加新标签
                foreach (var tagId in model.TagIds)
                {
                    var tag = await _unitOfWork.Tags.GetByIdAsync(tagId);
                    if (tag != null)
                    {
                        post.Tags.Add(tag);
                        tag.PostCount = tag.Posts.Count + 1;
                    }
                }
            }

            // 创建历史记录
            var history = new PostHistory
            {
                Title = post.Title,
                Content = post.Content,
                Summary = post.Summary,
                Version = post.History.Count + 1,
                Post = post
            };
            await _unitOfWork.PostHistories.AddAsync(history);

            await _unitOfWork.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除文章（需作者或管理员）
        /// </summary>
        /// <param name="id">文章ID</param>
        /// <returns>无内容</returns>
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> DeletePost(Guid id)
        {
            var post = await _unitOfWork.Posts.GetByIdAsync(id);
            if (post == null)
            {
                return NotFound();
            }

            var user = await _userManager.GetUserAsync(User);
            if (post.AuthorId != user.Id && !await _userManager.IsInRoleAsync(user, "Admin"))
            {
                return Forbid();
            }

            // 更新分类的文章计数
            if (post.Category != null)
            {
                post.Category.PostCount = post.Category.Posts.Count - 1;
            }

            // 更新标签的文章计数
            foreach (var tag in post.Tags.ToList())
            {
                post.Tags.Remove(tag);
                tag.PostCount = tag.Posts.Count - 1;
            }

            // 删除所有评论
            foreach (var comment in post.Comments.ToList())
            {
                await _unitOfWork.Comments.DeleteAsync(comment);
            }

            // 删除所有历史记录
            foreach (var history in post.History.ToList())
            {
                await _unitOfWork.PostHistories.DeleteAsync(history);
            }

            await _unitOfWork.Posts.DeleteAsync(post);
            await _unitOfWork.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 点赞文章（需登录）
        /// </summary>
        /// <param name="id">文章ID</param>
        /// <returns>无内容</returns>
        [HttpPost("{id}/like")]
        [Authorize]
        public async Task<ActionResult> LikePost(Guid id)
        {
            var post = await _unitOfWork.Posts.GetByIdAsync(id);
            if (post == null)
            {
                return NotFound();
            }

            post.LikeCount++;
            await _unitOfWork.SaveChangesAsync();

            return NoContent();
        }
    }
} 